import { routes, asyncRoutes } from '@/router'

const filterMenu = (asyncRoutes, roles) => {
  return asyncRoutes
    .filter(item => {
      return item.meta.role.includes(roles)
    })
    .map(item1 => {
      if (item1.children) {
        item1.children = filterMenu(item1.children, roles)
      }
      return item1
    })
}

const permission = {
  state: {
    constantRoutes: routes,
    allRoutes: []
  },
  mutations: {
    GET_PERMISSION_ROUTES(state, n) {
      state.allRoutes = state.constantRoutes.concat(n)
    }
  },
  actions: {
    getPermissionRoutes({ commit }, role) {
      return new Promise(resolve => {
        const filterRoutes = filterMenu(asyncRoutes, role)
        commit('GET_PERMISSION_ROUTES', filterRoutes)
        resolve(filterRoutes)
      })
    }
  }
}

export default permission
